package com.husong.controller;

import static com.husong.enums.AuthodType.jincongmin;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.husong.cons.CommonConstants;
import com.husong.cons.MessageCons;
import com.husong.cons.OrderCons;
import com.husong.cons.OrderConstants;
import com.husong.cons.ProgressCons;
import com.husong.cons.PushStr;
import com.husong.cons.ReturnCodeAndMsg;
import com.husong.cons.UserConstants;
import com.husong.controller.base.BaseController;
import com.husong.entity.Address;
import com.husong.entity.Complain;
import com.husong.entity.Conment;
import com.husong.entity.Evaluate;
import com.husong.entity.EvaluateDetail;
import com.husong.entity.Message;
import com.husong.entity.Order;
import com.husong.entity.OrderBroker;
import com.husong.entity.OrderDynamic;
import com.husong.entity.OrderIndexList;
import com.husong.entity.OrderInfo;
import com.husong.entity.OrderList;
import com.husong.entity.OrderProgress;
import com.husong.entity.OrderWaitList;
import com.husong.entity.PayDetail;
import com.husong.entity.User;
import com.husong.entity.Zan;
import com.husong.enums.UserType;
import com.husong.pojo.AdvertModel;
import com.husong.pojo.ConmentBean;
import com.husong.pojo.IndexModel;
import com.husong.pojo.OrderBrokerModel;
import com.husong.pojo.OrderProgressBean;
import com.husong.pojo.OrderTypeBean;
import com.husong.pojo.RedBean;
import com.husong.pojo.ReturnJsonBean;
import com.husong.pojo.TipBean;
import com.husong.pojo.UserWalletBean;
import com.husong.util.BeanUtil;
import com.husong.util.FlowUtil;
import com.husong.util.PointUtil;
import com.husong.util.UUIDUtil;

import cn.jpush.api.JPushClient;


/**
 * @author MaxMin.
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {
	public static long ORDER_LIMIT_TIME=120L;
	/**
	 * 测试
	 * @return
	 */
	@RequestMapping("/test")
	@ResponseBody
	public ReturnJsonBean test(String name,String text){
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			System.out.println(name+":"+text);
//			Timestamp currTime = new Timestamp(System.currentTimeMillis());
//			String orderId=UUIDUtil.getUUID();
//			String orderNo=FlowUtil.getFlowNo();
//			order.setOrderId(orderId);
//			order.setOrderNo(orderNo);
//			order.setCreateDate(currTime);
//			order.setIsdelete(0);//不删除
//			order.setNeedCancel(0);//不申请取消
//			order.setStatusId(1);//待抢单
//			int type=1;//默认为文字发单
//			if(order.getVoicePath()!=null&&!"".equals(order.getVoicePath().trim())){
//				type=2;//如果语音地址不为空，修改为语音发单
//			}
//			order.setType(type);
//			orderService.create(order, picpaths);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "OrderController", "publish()", e);
		}
		return rb;
	}
	
	/**
	 * 发布呼单
	 * @param order
	 * @return
	 */
	@RequestMapping("/publish")
    @ResponseBody
	public ReturnJsonBean publishOrder(Order order){
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			  Timestamp currTime = new Timestamp(System.currentTimeMillis());
			  final String orderId=UUIDUtil.getUUID();
			  String orderNo=FlowUtil.getFlowNo();
			  order.setOrderId(orderId);
			  order.setOrderNo(orderNo);
			  order.setCreateDate(currTime);
			  order.setIsdelete(0);//不删除
			  order.setNeedCancel(0);//不申请取消
			  order.setFee(BigDecimal.ZERO);
			  order.setDiscount(BigDecimal.ZERO);
			  order.setStatusId(OrderConstants.ORDER_NOT_GRAB);//待抢单
			  int type=OrderConstants.ORDER_WORD;//默认为文字发单
			  if(order.getVoicePath()!=null&&!"".equals(order.getVoicePath().trim())){
				  type=OrderConstants.ORDER_VOICE;//如果语音地址不为空，修改为语音发单
			  }
			  order.setType(type);
			  String[] picpaths={};
			  if(order.getPicurls()!=null&&!"".equals(order.getPicurls())){
				  picpaths=order.getPicurls().split(",");
			  }
			  orderService.create(order, picpaths);
			  
			  new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					//呼单状态记录
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_CREATE_MSG);
					progress.setContent(ProgressCons.ORDER_CREATE_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_NOT_GRAB);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderService.addOrderProgress(progress);
					
					JPushClient userClient = jPush.getUserClient();
					Set<String> tags=new HashSet<String>();
					tags.add(PushStr.TAG);
					jPush.pushWithTag(userClient, PushStr.ORDER_CREATE, tags);
				}
			}).start();
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "publishOrder()", e);
        }
		return rb;
	}
	
	
	/**
	 * 抢单
	 * @param order
	 * @return
	 */
	@RequestMapping("/grab")
    @ResponseBody
	public ReturnJsonBean grabOrder(String orderid,String userId,String lng,String lat){
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			//1、只有通过认证的经纪人才能抢单；2、不能抢自己发的单；3、2分钟之内不能连续抢单；
			//1.查询经纪人认证信息；2.查询订单信息；3.查询发单人信息；4.查询经纪人最后一次抢单时间；
			User broker=userService.get(userId);
			final Order order =orderService.get(orderid);
			User user=userService.get(order.getUserId());
			
			Timestamp lastGrabTime=orderService.getLastGrabOrderTimeByBrokerId(broker.getUserId());
			Timestamp currTime=new Timestamp(System.currentTimeMillis());
			long timeDiffer=180L;
			if(lastGrabTime!=null){
				timeDiffer=(currTime.getTime()-lastGrabTime.getTime())/1000;
			}
			
			if(timeDiffer<ORDER_LIMIT_TIME){
				returnFail(rb, ReturnCodeAndMsg.ORDER_LIMET_GRAB_TIME, ReturnCodeAndMsg.ORDER_LIMET_GRAB_TIME_MSG);
				return rb;
			}
			
			if(broker.getBrokerStatus()==null||broker.getIsbroker()==UserConstants.BROKER_NO||broker.getIsauthen()==UserConstants.AUTHEN_NOT){
				returnFail(rb, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_MSG);
				return rb;
			}
			if(broker.getBrokerStatus()==UserConstants.BROKER_DISABLE){
				returnFail(rb, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_ABLE, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_ABLE_MSG);
				return rb;
			}
			if(broker.getIsauthen()==UserConstants.AUTHEN_ING){
				returnFail(rb, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_PASS, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_PASS_MSG);
				return rb;
			}
			if(broker.getIsauthen()==UserConstants.AUTHEN_REFUSE){
				returnFail(rb, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_REFUSE, ReturnCodeAndMsg.ORDER_GRAB_NEED_AUTHEN_REFUSE_MSG);
				return rb;
			}
			if(user.getTelephone().equals(broker.getTelephone())){
				returnFail(rb, ReturnCodeAndMsg.ORDER_LIMT_BY_SELF, ReturnCodeAndMsg.ORDER_LIMT_BY_SELF_MSG);
				return rb;
			}
			
			if(order.getIsdelete()==CommonConstants.DELETE_YES){
				returnFail(rb, ReturnCodeAndMsg.ORDER_HAD_CANCLED, ReturnCodeAndMsg.ORDER_HAD_CANCLED_MSG);
				return rb;
			}
			
			if(order.getStatusId()>OrderConstants.ORDER_GRABED){
				returnFail(rb, ReturnCodeAndMsg.ORDER_HAD_CHECKED, ReturnCodeAndMsg.ORDER_HAD_CHECKED_MSG);
				return rb;
			}
			
			Integer count=orderService.getOrderBrokerCount(orderid, userId);
			if(count!=null&&count>0){
				returnFail(rb, ReturnCodeAndMsg.ORDER_HAD_GRABED, ReturnCodeAndMsg.ORDER_HAD_GRABED_MSG);
				return rb;
			}
			
			orderService.grabOrder(orderid, userId, lng, lat);
			final String userid=userId;
			final User u=user;
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					jPush.pushWithAlias(jPush.getUserClient(),OrderCons.COMPETED_STR, u.getNotifyid());
					
					Message message = new Message(OrderCons.COMPETED_STR,userid,MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
					//呼单状态记录
					Integer count=orderService.getProgeressCount(order.getOrderId(), OrderConstants.ORDER_GRABED);
					if(count==null||count<1){
						OrderProgress progress=new OrderProgress();
						progress.setId(UUIDUtil.getUUID());
						progress.setUser_msg(ProgressCons.ORDER_GRABED_MSG);
						progress.setContent(ProgressCons.ORDER_GRABED_CONTENT);
						progress.setOrderid(order.getOrderId());
						progress.setOrder_status(OrderConstants.ORDER_GRABED);
						progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
						orderService.addOrderProgress(progress);
					}
				}
			}).start();
			
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "grabOrder()", e);
        }
		return rb;
	}

    /**
     * 雇主任务中和历史订单
     *
     * @param key userid
     * @param type 1、任务中 2、历史订单
     * @param usertype 0、用户 1、经纪人
     *
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ReturnJsonBean list(String userId, Integer type, Integer usertype,Long lastDate,Long lastorderid) {
        ReturnJsonBean rb = new ReturnJsonBean();
        String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
        try {
            List<OrderList> list = new ArrayList<OrderList>();
            if (usertype == UserType.COMMON.getType()) {
                //查询用户的订单
                list = orderService.findOrdersByUserIdAndType(userId, type,lastDateStr,lastorderid);
            } else if (usertype == UserType.BROKER.getType()) {
                //查询经纪人订单
                list = orderService.findOrdersByBrokerAndType(userId, type,lastDateStr,lastorderid);
            }
            rb.setData(list);
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "list()", e);
        }
        return rb;
    }

    /**
     * 待接单列表
     * @param cityname 城市名
     * @param type 订单类型：代购、代办、代送
     */
    @RequestMapping("/wait/list")
    @ResponseBody
    public ReturnJsonBean waitList(String key,String cityname, Integer type,Long lastDate,Long lastorderid) {
        ReturnJsonBean rb = new ReturnJsonBean();
        String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
        try {
            List<OrderWaitList> list = orderService.findWaitOrders(key,cityname, type,lastDateStr,lastorderid);
            rb.setData(list);
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "waitList()", e);
        }
        return rb;
    }
    
    /**
     * 首页呼单列表
     * @param cityname 城市名
     */
    @RequestMapping("/index/list")
    @ResponseBody
    public ReturnJsonBean indexList(String cityname,Long lastDate,Long lastorderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<OrderIndexList> list = orderService.findIndexOrders(cityname, null,lastDateStr,lastorderid);
    		rb.setData(list);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "waitList()", e);
    	}
    	return rb;
    }
    /**
     * 
     * @param orderid
     * @param type 0表示雇主，1表示经纪人
     * @return
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ReturnJsonBean detail(String orderid,int type) {
        ReturnJsonBean rb = new ReturnJsonBean();
        try {
            OrderInfo order = orderService.getOrderInfo(orderid);
            Map<String,Object> params=new HashMap<String,Object>();
            if(type==0){
            	params.put("orderid", order.getOrderId());
            	params.put("userid", order.getUserId());
            }else{
            	params.put("orderid", order.getOrderId());
            	params.put("userid", order.getBrokerId());
            }
            Integer isEvaluated=orderService.getEvaluateCount(params);
            order.setIsEvaluated(isEvaluated);
            rb.setData(order);
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "detail()", e);
        }
        return rb;
    }
    
    @RequestMapping("/pay/detail")
    @ResponseBody
    public ReturnJsonBean pay_detail(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Order order = orderService.get(orderid);
    		UserWalletBean wallet=userService.getUsefullUserWalletBeanByUserId(order.getUserId());
    		if(wallet==null){
    			userService.addUserWallet(order.getUserId());
    			wallet=userService.getUsefullUserWalletBeanByUserId(order.getUserId());
    		}
    		PayDetail payDetail=new PayDetail();
    		payDetail.setDiscount(order.getDiscount());
    		payDetail.setFee(order.getFee());
    		payDetail.setOrderId(orderid);
    		payDetail.setTip(order.getTip());
    		payDetail.setBalance(wallet.getRecharge_amount());
    		rb.setData(payDetail);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "pay_detail()", e);
    	}
    	return rb;
    }

    @RequestMapping("/create")
    @ResponseBody
    public ReturnJsonBean create(Order order) {
        ReturnJsonBean rb = new ReturnJsonBean();
        try {
            int rt = orderService.create(order);
            if (rt > 0) {
                returnSuccess(rb);
            } else {
                returnFail(rb, ReturnCodeAndMsg.CREATE_ORDER_FAIL, ReturnCodeAndMsg.CREATE_ORDER_FAIL_MSG);
            }
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "create()", e);
        }
        return rb;
    }

    @RequestMapping("/cancel")
    @ResponseBody
    public ReturnJsonBean cancel(String orderid) {
        ReturnJsonBean rb = new ReturnJsonBean();
        try {
        	Order order=orderService.get(orderid);
        	if(order.getStatusId()>2){
        		returnFail(rb, ReturnCodeAndMsg.NEED_REQUEST_CANCEL, ReturnCodeAndMsg.NEED_REQUEST_CANCEL_MSG);
        		return rb;
        	}
            orderService.delete(orderid);
            returnSuccess(rb);
        } catch (Exception e) {
            e.printStackTrace();
            saveException(jincongmin.getName(), "OrderController", "cancel()", e);
        }
        return rb;
    }
    
    @RequestMapping("/agree/cancel")
    @ResponseBody
    public ReturnJsonBean agree_cancel(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
//    		Order order=orderService.get(orderid);
    		orderService.delete(orderid);
    		final String orderId=orderid;
    		new Thread(new Runnable() {
				
				@Override
				public void run() {
					Order order=orderService.get(orderId);
					
					User user =userService.get(order.getUserId());
					jPush.pushWithAlias(jPush.getUserClient(), OrderCons.CANCEL_STR, user.getNotifyid());
					Message message = new Message(OrderCons.CANCEL_STR,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
				}
			}).start();
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "cancel()", e);
    	}
    	return rb;
    }
    
    @RequestMapping("/need/cancel")
    @ResponseBody
    public ReturnJsonBean need_cancel(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Order order=orderService.get(orderid);
    		if(order.getNeedCancel()==1){
    			returnFail(rb, ReturnCodeAndMsg.CANNOT_REQUEST_CANCEL, ReturnCodeAndMsg.CANNOT_REQUEST_CANCEL_MSG);
    			return rb;
    		}
    		if(order.getStatusId()>7||order.getStatusId()<3){
    			returnFail(rb, ReturnCodeAndMsg.CANNOT_REQUEST_CANCEL, ReturnCodeAndMsg.CANNOT_REQUEST_CANCEL_MSG);
    			return rb;
    		}
    		final Order forder=order;
    		orderService.need_cancel(orderid);
    		new Thread(new Runnable() {
				
				@Override
				public void run() {
					User user =userService.get(forder.getBrokerId());
					jPush.pushWithAlias(jPush.getUserClient(), OrderCons.NEED_CANCEL, user.getNotifyid());
					Message message = new Message(OrderCons.NEED_CANCEL, forder.getBrokerId(),
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
				}
			}).start();
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "need_cancel()", e);
    	}
    	return rb;
    }
    
    /**
     * 选择经纪人列表
     * @param orderid
     * @param type（1、智能排序，2：距離排序，3、好評排序，4、成就排序）
     * @return
     */
    @RequestMapping("/choose/broker/list")
    @ResponseBody
    public ReturnJsonBean chooseBrokerList(String orderid,Integer type) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<OrderBroker> list=orderService.chooseBrokerList(orderid, type);
    		List<OrderBrokerModel> models=new ArrayList<OrderBrokerModel>();
    		for(OrderBroker orderBroker:list){
    			OrderBrokerModel model=BeanUtil.buildOrderBrokerModel(orderBroker);
    			models.add(model);
    		}
    		rb.setData(models);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "chooseBrokerList()", e);
    	}
    	return rb;
    }
    /**
     * 选择经纪人
     * @param orderid
     * @param type（1、智能排序，2：距離排序，3、好評排序，4、成就排序）
     * @return
     */
    @RequestMapping("/choose/broker")
    @ResponseBody
    public ReturnJsonBean chooseBroker(String orderbrokerid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.chooseBroker(orderbrokerid);
    		
    		
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "chooseBroker()", e);
    	}
    	return rb;
    }
    /**
     * 已购买
     * @param orderid
     * @param fee
     * @param adverttype
     * @return
     */
    @RequestMapping("/buy")
    @ResponseBody
    public ReturnJsonBean buy(String orderid,Double fee) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.buy(orderid, BigDecimal.valueOf(fee));
    		
    		final String orderId=orderid;
    		new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					
					Order order =orderService.get(orderId);
					User user=userService.get(order.getUserId());
					jPush.pushWithAlias(jPush.getUserClient(),OrderCons.PURCHASED_STR, user.getNotifyid());
					
					Message message = new Message(OrderCons.PURCHASED_STR,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
					//呼单状态记录
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_BUYED_MSG);
					progress.setContent(ProgressCons.ORDER_BUYED_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_HAD_BUY);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderService.addOrderProgress(progress);
				}
			}).start();
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "buy()", e);
    	}
    	return rb;
    }
    
    /**
     * 确认完成
     * @param orderid
     * @return
     */
    @RequestMapping("/confirm")
    @ResponseBody
    public ReturnJsonBean confirm(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.confirm(orderid);
    		
    		final String orderId=orderid;
    		new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					Order order =orderService.get(orderId);
					User user=userService.get(order.getBrokerId());
					jPush.pushWithAlias(jPush.getUserClient(), OrderCons.CONFROM_COMPLET, user.getNotifyid());
					
					Message message = new Message(OrderCons.CONFROM_COMPLET, order.getBrokerId(),
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
				}
			}).start();
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "confirm()", e);
    	}
    	return rb;
    }
    /**
     * 已取货
     * @param orderid
     * @return
     */
    @RequestMapping("/got")
    @ResponseBody
    public ReturnJsonBean got(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.got(orderid);
    		
    		final String orderId=orderid;
    		new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					Order order =orderService.get(orderId);
					
					User user=userService.get(order.getUserId());
					jPush.pushWithAlias(jPush.getUserClient(),
							OrderCons.COLLECTED_STR, user.getNotifyid());
					
					Message message = new Message(OrderCons.COLLECTED_STR,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderService.addMessage(message);
					//呼单状态记录
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_COLLECT_MSG);
					progress.setContent(ProgressCons.ORDER_COLLECT_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_HAD_GET_THING);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderService.addOrderProgress(progress);
				}
			}).start();
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "got()", e);
    	}
    	return rb;
    }
    /**
     * 已办完
     * @param orderid
     * @return
     */
    @RequestMapping("/dealed")
    @ResponseBody
    public ReturnJsonBean dealed(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.dealed(orderid);
    		
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "dealed()", e);
    	}
    	return rb;
    }
    
    /**
     * 余额支付
     * @param orderid
     * @return
     */
    @RequestMapping("/balance/pay")
    @ResponseBody
    public ReturnJsonBean balance_pay(String orderid,String redid,String password,String user_id) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		UserWalletBean wallet=userService.getUsefullUserWalletBeanByUserId(user_id);
    		if(wallet==null){
    			userService.addUserWallet(user_id);
    			wallet=userService.getUsefullUserWalletBeanByUserId(user_id);
    		}
    		
    		if(!password.equals(wallet.getPay_password())){
    			returnFail(rb, ReturnCodeAndMsg.WALLET_PASSWORD_ILLEGAL, ReturnCodeAndMsg.WALLET_PASSWORD_ILLEGAL_MSG);
    			return rb;
    		}
    		
    		//进行余额支付
    		
    		rb=orderService.walletPay(user_id, orderid, redid);
    		
//    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "dealed()", e);
    	}
    	return rb;
    }
    
    /**
     * 呼单状态
     * @param orderid
     * @return
     */
    @RequestMapping("/progress")
    @ResponseBody
    public ReturnJsonBean progress(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<OrderProgress> list=orderService.getOrderProgressesByOrderId(orderid);
    		List<OrderProgressBean> beans=new ArrayList<OrderProgressBean>();
    		for(OrderProgress progress:list){
    			OrderProgressBean bean=BeanUtil.buildOrderProgress(progress);
    			beans.add(bean);
    		}
    		rb.setData(beans);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "progress()", e);
    	}
    	return rb;
    }
    
    /**
     * 获取小费列表
     * @return
     */
    @RequestMapping("/get/tips")
    @ResponseBody
    public ReturnJsonBean getTips() {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<TipBean> list=orderService.getTips();
    		rb.setData(list);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getTips()", e);
    	}
    	return rb;
    }
    /**
     * 获取订单类型列表
     * @return
     */
    @RequestMapping("/get/types")
    @ResponseBody
    public ReturnJsonBean getOrderTypes() {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<OrderTypeBean> list=orderService.getOrderTypes();
    		rb.setData(list);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getOrderTypes()", e);
    	}
    	return rb;
    }
    
    /**
     * 获取订单类型列表
     * @return
     */
    @RequestMapping("/get/addresses")
    @ResponseBody
    public ReturnJsonBean getAddresses(String userId) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<Address> list=orderService.getAddresses(userId);
    		rb.setData(list);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getAddresses()", e);
    	}
    	return rb;
    }
    
    /**
     * 添加常用地址
     * @return
     */
    @RequestMapping("/add/address")
    @ResponseBody
    public ReturnJsonBean addAddress(String userId,String name,String telephone,String text) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Address address=new Address();
    		String addressid=UUIDUtil.getUUID();
    		address.setAddressid(addressid);
    		address.setCreate_date(new Timestamp(System.currentTimeMillis()));
    		address.setName(name);
    		address.setTelephone(telephone);
    		address.setText(text);
    		address.setUser_id(userId);
    		orderService.addAddress(address);
    		rb.setData(address);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "addAddress()", e);
    	}
    	return rb;
    }
    
    /**
     * 更新常用地址
     * @return
     */
    @RequestMapping("/update/address")
    @ResponseBody
    public ReturnJsonBean updateAddress(String userId,String addressid,String name,String telephone,String text) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Address address=new Address();
    		address.setAddressid(addressid);
    		address.setCreate_date(new Timestamp(System.currentTimeMillis()));
    		address.setUpdate_date(new Timestamp(System.currentTimeMillis()));
    		address.setName(name);
    		address.setTelephone(telephone);
    		address.setText(text);
    		address.setUser_id(userId);
    		orderService.updateAddress(address);
//    		rb.setData(address);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "updateAddress()", e);
    	}
    	return rb;
    }
    
    /**
     * 删除常用地址
     * @return
     */
    @RequestMapping("/delete/address")
    @ResponseBody
    public ReturnJsonBean deleteAddress(String addressid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.deletAddress(addressid);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "deleteAddress()", e);
    	}
    	return rb;
    }
    
    
    /**
     * 获取广告
     * @return
     */
    @RequestMapping("/index/advert")
    @ResponseBody
    public ReturnJsonBean getAdvert(String cityname) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<AdvertModel> list=orderService.getAdverts(cityname);
    		IndexModel model=new IndexModel();
    		model.setAdverts(list);
    		model.setBrokerCount(orderService.getBrokerCounts(cityname));
    		rb.setData(model);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getAdvert()", e);
    	}
    	return rb;
    }
    
    /**
     * 添加评论
     * @return
     */
    @RequestMapping("/evaluate/add")
    @ResponseBody
    public ReturnJsonBean evaluate_add(String orderid,String userid,String content,Double point) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.addEvaluate(orderid, userid, content, BigDecimal.valueOf(point));
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_add()", e);
    	}
    	return rb;
    }
    /**
     * 评论列表
     * 1:我对经纪人，2：经纪人对我，3：我对雇主，4：雇主对我
     * @return
     */
    @RequestMapping("/evaluate/list")
    @ResponseBody
    public ReturnJsonBean evaluate_list(String user_id,Long lastDate,Long lastrowid,int type) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	if(lastDate==null||lastDate==0){
    		lastDateStr=sdf.format(new Date());
    	}else{
    		lastDateStr=sdf.format(lastDate);
    	}
    	try {
    		List<Evaluate> evaluates=null;
    		if(type==1){
    			evaluates =orderService.getMeToBrokerEvalustes(user_id,lastDateStr,lastrowid);
    		}else if(type==2){
    			evaluates =orderService.getBrokerToMeEvalustes(user_id,lastDateStr,lastrowid);
    		}else if(type==3){
    			evaluates =orderService.getMeToUserEvalustes(user_id,lastDateStr,lastrowid);
    		}else if(type==4){
    			evaluates =orderService.getUserToMeEvalustes(user_id,lastDateStr,lastrowid);
    		}
    		rb.setData(evaluates);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_list()", e);
    	}
    	return rb;
    }
    
    /**
     * 经纪人对我评论
     * @return
     */
    @RequestMapping("/evaluate/broker/to/me")
    @ResponseBody
    public ReturnJsonBean evaluate_broker_to_me(String user_id,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<Evaluate> evaluates =orderService.getBrokerToMeEvalustes(user_id,lastDateStr,lastrowid);
    		rb.setData(evaluates);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_broker_to_me()", e);
    	}
    	return rb;
    }
    /**
     * 我对雇主评价
     * @return
     */
    @RequestMapping("/evaluate/me/to/user")
    @ResponseBody
    public ReturnJsonBean evaluate_me_to_user(String user_id,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<Evaluate> evaluates =orderService.getMeToUserEvalustes(user_id,lastDateStr,lastrowid);
    		rb.setData(evaluates);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_me_to_user()", e);
    	}
    	return rb;
    }
    /**
     * 雇主对我评论
     * @return
     */
    @RequestMapping("/evaluate/user/to/me")
    @ResponseBody
    public ReturnJsonBean evaluate_user_to_me(String user_id,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<Evaluate> evaluates =orderService.getUserToMeEvalustes(user_id,lastDateStr,lastrowid);
    		rb.setData(evaluates);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_user_to_me()", e);
    	}
    	return rb;
    }
    /**
     * 我对经纪人评价
     * @return
     */
    @RequestMapping("/evaluate/me/to/broker")
    @ResponseBody
    public ReturnJsonBean evaluate_me_to_broker(String user_id,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<Evaluate> evaluates =orderService.getMeToBrokerEvalustes(user_id,lastDateStr,lastrowid);
    		rb.setData(evaluates);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_me_to_broker()", e);
    	}
    	return rb;
    }
    
    
    /**
     * 评价详情
     * 0:雇主，1：经纪人
     * @return
     */
    @RequestMapping("/evaluate/detail")
    @ResponseBody
    public ReturnJsonBean evaluate_detail(String orderid,int type) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		EvaluateDetail detail=new EvaluateDetail();
    		if(type==0){
    			Order order=orderService.get(orderid);
        		User user=userService.get(order.getUserId());
        		detail.setDeclaration(user.getDeclaration());
        		detail.setOrderId(orderid);
        		detail.setPoint(user.getPoint());
        		detail.setStars(user.getStars());
        		detail.setTitle(PointUtil.convertToTitle(user.getPoint()));
        		detail.setUsername(user.getUsername());
        		detail.setHeader(user.getHeader());
    		}else if(type==1){
    			Order order=orderService.get(orderid);
        		User user=userService.get(order.getBrokerId());
        		detail.setDeclaration(user.getDeclaration());
        		detail.setOrderId(orderid);
        		detail.setPoint(user.getPoint());
        		detail.setStars(user.getStars());
        		detail.setTitle(PointUtil.convertToTitle(user.getPoint()));
        		detail.setUsername(user.getUsername());
        		detail.setHeader(user.getHeader());
    		}
    		rb.setData(detail);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "evaluate_detail()", e);
    	}
    	return rb;
    }
    
    /**
     * 评论列表
     * @return
     */
    @RequestMapping("/comment/list")
    @ResponseBody
    public ReturnJsonBean comment_list(String orderid,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<ConmentBean> beans=orderService.getComments(orderid, lastDateStr, lastrowid);
    		List<Conment> conments=new ArrayList<Conment>();
    		for(ConmentBean bean:beans){
    			Conment conment=BeanUtil.build(bean);
    			conments.add(conment);
    		}
    		rb.setData(conments);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "comment_list()", e);
    	}
    	return rb;
    }
    
    /**
     * 呼单动态
     * @return
     */
    @RequestMapping("/dynamic")
    @ResponseBody
    public ReturnJsonBean dynamic(String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	
    	try {
    		OrderDynamic dynamic=new OrderDynamic();
    		Order order =orderService.get(orderid);
    		Integer cCount=orderService.getConmentCount(orderid);
    		Integer zCount=orderService.getZanCount(orderid);
    		List<Zan> zans=orderService.getZans(orderid);
    		dynamic.setcCount(cCount);
    		dynamic.setDesc(order.getDesc());
    		dynamic.setFromAddress(order.getFromAddress());
    		dynamic.setOrderId(orderid);
    		dynamic.setOrderNo(order.getOrderNo());
    		dynamic.setPicpaths(order.getPicpaths());
    		dynamic.setTip(order.getTip());
    		dynamic.setToAddress(order.getToAddress());
    		dynamic.setType(order.getType());
    		dynamic.setuHeader(order.getuHeader());
    		dynamic.setVoicePath(order.getVoicePath());
    		dynamic.setOrderTypeId(order.getOrderTypeId());
    		dynamic.setzCount(zCount);
    		dynamic.setZans(zans);
    		rb.setData(dynamic);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "dynamic()", e);
    	}
    	return rb;
    }
    
    /**
     * 呼单回复
     * @return
     */
    @RequestMapping("/comment/add")
    @ResponseBody
    public ReturnJsonBean conment_add(String user_id,String order_id,String parent_comment_id,String content) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.addConment(user_id, order_id, parent_comment_id, content);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "dynamic()", e);
    	}
    	return rb;
    }
    
    /**
     * 呼单点赞
     * @return
     */
    @RequestMapping("/zan")
    @ResponseBody
    public ReturnJsonBean zan(String user_id,String order_id) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Map<String,Object> map=new HashMap<String,Object>();
    		map.put("zan_flag", orderService.addZan(user_id, order_id));
    		rb.setData(map);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "zan()", e);
    	}
    	return rb;
    }
    
    /**
     * 追加小费
     * @return
     */
    @RequestMapping("/append/tip")
    @ResponseBody
    public ReturnJsonBean append_tip(int tipid,String orderid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		orderService.appendTip(tipid, orderid);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "append_tip()", e);
    	}
    	return rb;
    }
    
    /**
     * 投诉
     * @return
     */
    @RequestMapping("/complain")
    @ResponseBody
    public ReturnJsonBean complain(String userid,String orderid,String text,String telephone) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		Complain complain=new Complain();
    		complain.setCreatetime(new Timestamp(System.currentTimeMillis()));
    		complain.setOrder_id(orderid);
    		complain.setTelephone(telephone);
    		complain.setText(text);
    		complain.setUser_id(userid);
    		orderService.complain(complain);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "complain()", e);
    	}
    	return rb;
    }
    
    /**
     * 红包列表
     * @return
     */
    @RequestMapping("/get/reds")
    @ResponseBody
    public ReturnJsonBean getReds(String user_id,int type) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	try {
    		List<RedBean> beans=null;
    		if(type==1){
    			beans=orderService.getUsefullReds(user_id);
    		}else if(type==2){
    			beans=orderService.getReds(user_id);
    		}
    		rb.setData(beans);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getReds()", e);
    	}
    	return rb;
    }
    
    /**
     * 呼送消息
     * type：1表示通知，2表示动态
     * @return
     */
    @RequestMapping("/get/messages")
    @ResponseBody
    public ReturnJsonBean getMessages(String userid,int type,Long lastDate,Long lastrowid) {
    	ReturnJsonBean rb = new ReturnJsonBean();
    	String lastDateStr="";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(lastDate==null||lastDate==0){
        	lastDateStr=sdf.format(new Date());
        }else{
        	lastDateStr=sdf.format(lastDate);
        }
    	try {
    		List<Message> messages=orderService.getMessages(userid, type, lastDateStr, lastrowid);
    		rb.setData(messages);
    		returnSuccess(rb);
    	} catch (Exception e) {
    		e.printStackTrace();
    		saveException(jincongmin.getName(), "OrderController", "getMessages()", e);
    	}
    	return rb;
    }
    
    
    
    
    
}
